package com.ignou.mca.exam;

import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import sun.reflect.ReflectionFactory.GetReflectionFactoryAction;

import com.ignou.mca.beans.ExamStatusBean;
import com.ignou.mca.beans.PaymentBean;
import com.ignou.mca.datasource.DatabaseOperations;

/**
 * Servlet implementation class Payment
 */
public class Payment extends HttpServlet 
{
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Payment() 
    {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		// TODO Auto-generated method stub
		String payment = request.getParameter("examFees");
		String examId = request.getParameter("examId");
		String examName = request.getParameter("examName");
		String subjectId = request.getParameter("subjectId");
		String userName = request.getParameter("userName");
		
		PaymentBean pb = new PaymentBean();
		pb.setExamFees(Integer.parseInt(payment));
		pb.setExamId(Integer.parseInt(examId));
		pb.setSubjectId(Integer.parseInt(subjectId));
		pb.setUserName(userName);
		
		ServletContext ctx = getServletContext();
		DatabaseOperations db = new DatabaseOperations();
		Boolean isPaySuccess = db.doPayment(pb);
		HttpSession session = request.getSession();
		
		if(isPaySuccess)
		{
			ExamStatusBean esb = new ExamStatusBean();
			esb.setExamId(Integer.parseInt(examId));
			esb.setResult("enrolled");
			esb.setScore(0);
			esb.setSubjectId(Integer.parseInt(subjectId));
			esb.setUserName(userName);
			Boolean b = db.addExamStatus(esb);
			if(b)
			{
				ctx.getRequestDispatcher("/PaymentSuccess.jsp").forward(request, response);
			}else
			{
				session.setAttribute("ErrorMessage", "Unable to to contact server at this time. <br>Please try again after sometime.");
				ctx.getRequestDispatcher("/ErrorDisplay.jsp").forward(request, response);
			}
		}
		else
		{
			session.setAttribute("ErrorMessage", "Payment process is unsuccessful.<br>Please try again after sometime.");
			ctx.getRequestDispatcher("/ErrorDisplay.jsp").forward(request, response);
		}
	}

}
